let AudioManager = require('AudioManager')
let isWX = cc.sys.browserType == cc.sys.BROWSER_TYPE_WECHAT_GAME;

const WX = {
  GAME_VERSION: '1.0.6',
  canVibrate: true,
  isWX(){
    return isWX;
  },
  login () {
    if (!isWX) return
    console.log('WX-login')
    this.shareEnable = false
    this.shareConfig = [
      {
        id: 0,
        title: '这个小游戏是在太爽了！',
        url: 'https://tinycar-1254461739.file.myqcloud.com/share/0.jpg'
      }
    ]

    cc.loader.load(
      'https://tinycar-1254461739.cos.ap-chengdu.myqcloud.com/share/share.json',
      (err, json) => {
        console.log('share config error!', err)
        if (!err) {
          if (json[0].enable == '0' && json[0].version == this.GAME_VERSION) {
            this.shareEnable = false
          } else {
            this.shareEnable = true
            json.splice(0, 1)
            this.shareConfig = json
          }
          console.log('share enable:', this.shareEnable)
          console.log('share config:', this.shareConfig)
        }
      }
    )

    wx.showShareMenu({
      withShareTicket: true
    })

    wx.updateShareMenu({
      withShareTicket: true
    })

    wx.onShareAppMessage(() => ({
      title: this.shareConfig[Math.floor(Math.random() * this.shareConfig.length)].title,
      imageUrl: this.shareConfig[Math.floor(Math.random() * this.shareConfig.length)].url
    }))

    // this.showBannerAd()

    if (!this.rewardedVideoAd) {
      this.rewardedVideoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-74ceb4c131453d04'
      })
      this.rewardedVideoAd.onLoad(() => {
        this.isVideoAvailable = true
      })
      this.rewardedVideoAd.onError(err => {
        console.log(err)
        this.isVideoAvailable = false
      })
    }

    this.wxTxButton = wx.createFeedbackButton({
      type: 'image',
      image: 'imgs/TXButton.png',
      style: {
        left: 0,
        top: 0,
        width: 48.8,
        height: 30.4,
        lineHeight: 40,
        backgroundColor: '#ff0000',
        color: '#ffffff',
        textAlign: 'center',
        fontSize: 16,
        borderRadius: 4
      }
    })
  },





  showBannerAd (func) {
    if (!isWX) return
    console.log("WX-showBannerAd");
    if (!this.bannerAd) {
      let { screenWidth, screenHeight } = wx.getSystemInfoSync()
      this.bannerAd = wx.createBannerAd({
        adUnitId: 'adunit-33e33964203797c4',
        style: {
          width: 300,
          left: (screenWidth - 300) / 2,
          top: screenHeight - 86
        }
      })
      this.bannerAd.onResize(res => {
        if(this.bannerAd){
          this.bannerAd.style.left = (screenWidth - res.width) / 2
          this.bannerAd.style.top = screenHeight - res.height
        }
      })

      this.bannerAd.onError(function (err) {
        console.log('bannerAd onError.', err)
      })
    }

    if (this.bannerAd) {
      this.bannerAd.show()
        .then(() => {
          if(func) func();
          console.log('banner 广告显示')
        })
        .catch(err => console.log(err))
    }
  },
  hideBannerAd () {
    if (!isWX || !this.bannerAd) return
    this.bannerAd.hide()
    this.bannerAd.destroy()
    this.bannerAd = null
  },

  watchVideoAD (callback) {
    console.log('WX-watchVideoAD')
    // AudioManager.instance.stopAll()
    console.log("isVideoAvailable",this.isVideoAvailable);
    if (this.isVideoAvailable) {
      this.rewardedVideoAd.show()
      let onClose = res => {
        // AudioManager.instance.play('bgm')
        if ((res && res.isEnded) || res === undefined) {
          if (callback) callback()
        }
        this.rewardedVideoAd.offClose(onClose)
        this.isVideoAvailable = false
      }
      this.rewardedVideoAd.onClose(onClose)
    }
  },

  navigateToMiniP (appId, path) {
    if (!isWX) return
    let envVersion = 'release' // develop || trial || release;
    if(wx.navigateToMiniProgram){
      wx.navigateToMiniProgram({
        appId, // string		是	要打开的小程序 appId
        path, // string		否	打开的页面路径，如果为空则打开首页
        // extraData:	// object		否	需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据。
        envVersion, // string	release	否	要打开的小程序版本。仅在当前小程序为开发版或体验版时此参数有效。如果当前小程序是正式版，则打开的小程序必定是正式版。
        success () {
          // function		否	接口调用成功的回调函数
          console.log('跳转成功！')
        },
        fail () {
          // function		否	接口调用失败的回调函数
          console.log('跳转失败！')
        },
        complete () {
          // function		否	接口调用结束的回调函数（调用成功、失败都会执行）
          console.log('跳转操作完成！')
        }
      })
    }
  },

  getShareInfo () {
    if (!isWX) return
    console.log('WX-getShareInfo')
    let index = Math.floor(Math.random() * this.shareConfig.length)
    return this.shareConfig[index]
  },

  share (success, fail) {
    if (!this.shareEnable) return
    console.log('WX-share')
    let shareInfo = this.getShareInfo()
    let startTime = Date.now()

    AudioManager.instance.stopAll()
    wx.onShow(function onShowShare (res) {
      AudioManager.instance.play('bgm')
      console.log('wx.onShow')
      wx.offShow(onShowShare)
      let endTime = Date.now()
      if (endTime - startTime < 3700) {
        let msg = [
          '短时间内，不要分享同一个群',
          '请换个群试试哦~',
          '网络开小差了，请重新试试',
          '这个群分享太多次了，分享到其他群试试吧！',
          '请分享到不同的群'
        ]
        wx.showToast({
          title: msg[Math.floor(Math.random() * msg.length)],
          icon: 'none',
          duration: 2000
        })
        console.log('wx.onShow-fail')
        if (fail) fail()
      } else {
        console.log('wx.onShow-success')
        if (success) success()
      }
    })

    // stopall
    wx.shareAppMessage({
      title: '这个小游戏是在太爽了！',
      imageUrl: 'https://tinycar-1254461739.file.myqcloud.com/share/0.jpg'
    })

    // wx.shareAppMessage({
    //     title: shareInfo.title,
    //     imageUrl: shareInfo.url,
    // });
  },

  vibrate (isLong) {
    if(!this.canVibrate) return;
    if (!isWX) return
    let func = isLong ? wx.vibrateLong : wx.vibrateShort
    func({
      success () {
        console.log('WX-vibrate success')
      },
      fail () {
        console.log('WX-vibrate fail')
      },
      complete () {
        console.log('WX-vibrate complete')
      }
    })
  },

  ald: {
    sendEventChapterPass (chapterLevel, passTime) {
      if (!isWX) return
      console.log("WX.ald-sendEvent-chapterPass")
      wx.aldSendEvent('chapterPass', {
        'chapterLevel': chapterLevel,
        'passTime': passTime
      })
    },
    sendEventBuyCar (carLevel, curMoney, useMoney) {
      if (!isWX) return
      console.log("WX.ald-sendEvent-buyCar")
      wx.aldSendEvent('buyCar', {
        'carLevel': carLevel,
        'curMoney': curMoney,
        'useMoney': useMoney
      })
    }
  }
}

module.exports = WX
